% Get the life time for unfolding and refolding states of 2state models
clear all;
sampling_freq=175; % sampling frequecy in herz
time_offset_step=0.005;
time_offset_cap=1;
filename='G:\Mingxi\Dropbox\yingjian guo\Alphacat\constant_force\20140728_his_alphacat_bead063_s2_extension_driftcorrected_fitting';
readfile = sprintf('%s%s',filename,'.dat');
file=importdata(readfile);
hmmd_states=file.data(:,1);
currentstates=0;
startseq=1;
endseq=1;
states=[];
states1=[];
states2=[];
for i=1:1:(size(hmmd_states)-1)
    if hmmd_states(i)~= hmmd_states(i+1)
        endseq=i;
        states=[states; currentstates hmmd_states(i) startseq endseq ((endseq-startseq+1)/sampling_freq)];
        if currentstates
            states1=[states1; currentstates hmmd_states(i) startseq endseq ((endseq-startseq+1)/sampling_freq)];
        else
            states2=[states2; currentstates hmmd_states(i) startseq endseq ((endseq-startseq+1)/sampling_freq)];
        end
        startseq=i+1;
        currentstates=~currentstates;
    end
end

%Do a lilliefor test on whether the data is exponentially distributed, if
%not introduce a flexible cutoff time
state1_offset=0;
state2_offset=0;
state1_lifetime=states1(:,5);
state2_lifetime=states2(:,5);
state1_lifetime_woffset=state1_lifetime;
state2_lifetime_woffset=state2_lifetime;
while lillietest(state1_lifetime_woffset,'Distr','exp') && state1_offset < time_offset_cap
    state1_offset=state1_offset+time_offset_step;
    state1_lifetime_woffset=state1_lifetime((state1_lifetime-state1_offset)>0)-state1_offset;
end

while lillietest(state2_lifetime_woffset,'Distr','exp') && state2_offset < time_offset_cap
    state2_offset=state2_offset+time_offset_step;
    state2_lifetime_woffset=state2_lifetime((state2_lifetime-state2_offset)>0)-state2_offset;
end
[mu1 delta1]=expfit(state1_lifetime_woffset);
[mu2 delta2]=expfit(state2_lifetime_woffset);
filename = sprintf('%s%s',filename,'-step-lifetime-test.dat');
fid = fopen(filename,'w');
fprintf(fid,'states\thmmvalue\tstart\tend\tlifetime(s)\n');
fprintf(fid,'%d\t%f\t%d\t%d\t%f\t\n',states');
fclose(fid);
filename = sprintf('%s%s',filename,'-step-lifetime-fit-test.dat');
fid = fopen(filename,'w');
fprintf(fid,'states\thmmvalue\tmu\tupper\tlower(s)\tTime offset\n');
fprintf(fid,'%d\t%f\t%f\t%f\t%f\t%f\n',0,states1(1,2)',1\mu1,delta1,state1_offset);
fprintf(fid,'%d\t%f\t%f\t%f\t%f\t%f\n',1,states2(1,2)',1\mu2,delta2,state2_offset);
fclose(fid);